HTML Web Storage API

    Web Storage

    In HTML5 W3C (World Wide Web Consortium) introduced the concept of web-storage. Web Storages allow the developer to store the user data within the user's browser. Web browsers introduced as an alternative for cookies storages that required server request. Web storage provides more security and data space for the user confidential data and does not affect website performance. As compared to the cookies, web storage provides far larger storage size(approx 5MB) and the data of web storage does not send back to the server.

    Web Storage Objects

    We can use two types of web storage objects to store the user's data.

    • localStorage
    • sessionStorage

    1. LocalStorage Object

    With localStorage object, we can store the user's data without expiration. The data will remain in the user browser until or unless the user manually delete the data or the entire browser.

    Example

    <script>
    
            localStorage.setItem("name", "sam");
     
            document.write(localStorage.getItem("name"));
    </script>

    localStorage.setItem("name", "sam"); statement create a localStorage object by name="name" and value ="sam". And the localStorage.getItem("name") retrieve the value of for the name object. The above example can also be written as:

    <script>         
    localStorage.name="sam";
    document.write(localStorage.name);
    </script>

    2. SessionStorage Object

    The sessionStorage is similar to localStorage but its data gets deleted once the session end or the user closes the tab or browser.

    Example

    <script>         
    sessionStorage.name="sam"; 
    document.write(sessionStorage.name); 
    </script>

    Summary

    • Web storages allow the developer to store confidential client data within the client's browser.
    • There are two types of web storage objects localStorage and sessionStorage.
    • localStorage data does not expire with time.
    • sessionStorage data gets expire once the user closes the tab or browser.